const questionService = require('../../../services/question');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0,
    subjects: ['语文', '数学', '英语'],
    subjectIndex: 0,
    excelTempUrl: '',
    uploadProgress: 0,
    importResult: null,
    ocrImage: '',
    ocrResult: null,
    ocrLoading: false,
    // 手动添加
    manualForm: {
      type: 'single_choice',
      subject: '语文',
      stem: '',
      options: ['', '', '', ''],
      answer: '',
      analysis: '',
      difficulty: 3,
      knowledge: []
    },
    // 类型选项
    typeOptions: [
      { value: 'single_choice', label: '单选题' },
      { value: 'multiple_choice', label: '多选题' },
      { value: 'true_false', label: '判断题' },
      { value: 'fill_blank', label: '填空题' },
      { value: 'short_answer', label: '简答题' }
    ],
    // 难度选项
    difficultyOptions: [
      { value: 1, label: '简单' },
      { value: 2, label: '较简单' },
      { value: 3, label: '中等' },
      { value: 4, label: '较难' },
      { value: 5, label: '困难' }
    ],
    // 知识点列表
    knowledgeList: [],
    showKnowledgePopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 加载知识点列表
    this.getKnowledgeList();
  },

  /**
   * 切换标签页
   */
  onTabChange(event) {
    this.setData({
      activeTab: event.detail.index
    });
  },

  /**
   * 选择学科
   */
  onSubjectChange(event) {
    const subjectIndex = event.detail.value;
    const subject = this.data.subjects[subjectIndex];
    
    // 更新表单学科
    this.setData({
      subjectIndex,
      'manualForm.subject': subject
    });
    
    // 重新获取知识点列表
    this.getKnowledgeList();
  },

  /**
   * 获取知识点列表
   */
  async getKnowledgeList() {
    try {
      // 显示加载
      wx.showLoading({
        title: '加载中',
      });
      
      const subject = this.data.manualForm.subject;
      
      // 调用云函数获取知识点
      const result = await wx.cloud.callFunction({
        name: 'getKnowledgePoints',
        data: {
          subject
        }
      });
      
      // 隐藏加载
      wx.hideLoading();
      
      if (result.result.success) {
        this.setData({
          knowledgeList: result.result.knowledgePoints
        });
      } else {
        wx.showToast({
          title: result.result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      // 隐藏加载
      wx.hideLoading();
      
      console.error('获取知识点失败', error);
      wx.showToast({
        title: '获取知识点失败',
        icon: 'none'
      });
    }
  },

  /**
   * 下载Excel模板
   */
  downloadTemplate() {
    // 显示加载
    wx.showLoading({
      title: '下载中',
    });
    
    // 获取云存储中的模板文件
    wx.cloud.downloadFile({
      fileID: 'cloud://xxx.xxx/templates/question_template.xlsx',
      success: res => {
        // 隐藏加载
        wx.hideLoading();
        
        const filePath = res.tempFilePath;
        
        // 打开文件
        wx.openDocument({
          filePath: filePath,
          showMenu: true,
          success: function(res) {
            console.log('打开文档成功');
          },
          fail: function(error) {
            console.error('打开文档失败', error);
            wx.showToast({
              title: '打开文档失败',
              icon: 'none'
            });
          }
        });
      },
      fail: error => {
        // 隐藏加载
        wx.hideLoading();
        
        console.error('下载模板失败', error);
        wx.showToast({
          title: '下载模板失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 上传Excel文件
   */
  uploadExcelFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['xlsx', 'xls'],
      success: res => {
        const tempFile = res.tempFiles[0];
        
        // 检查文件类型
        if (!tempFile.name.endsWith('.xlsx') && !tempFile.name.endsWith('.xls')) {
          wx.showToast({
            title: '请选择Excel文件',
            icon: 'none'
          });
          return;
        }
        
        // 显示加载
        wx.showLoading({
          title: '上传中',
        });
        
        // 上传文件到云存储
        const uploadTask = wx.cloud.uploadFile({
          cloudPath: `excel/${Date.now()}-${Math.random().toString(36).substr(2)}.xlsx`,
          filePath: tempFile.path,
          success: res => {
            // 隐藏加载
            wx.hideLoading();
            
            // 获取文件ID
            const fileID = res.fileID;
            
            // 保存文件ID
            this.setData({
              excelTempUrl: fileID
            });
            
            // 导入Excel数据
            this.importExcelData(fileID);
          },
          fail: error => {
            // 隐藏加载
            wx.hideLoading();
            
            console.error('上传文件失败', error);
            wx.showToast({
              title: '上传文件失败',
              icon: 'none'
            });
          }
        });
        
        // 监听上传进度
        uploadTask.onProgressUpdate(res => {
          this.setData({
            uploadProgress: res.progress
          });
        });
      }
    });
  },

  /**
   * 导入Excel数据
   */
  async importExcelData(fileID) {
    try {
      // 显示加载
      wx.showLoading({
        title: '导入中',
      });
      
      // 调用服务导入试题
      const result = await questionService.importQuestionsFromExcel(fileID);
      
      // 隐藏加载
      wx.hideLoading();
      
      if (result.success) {
        this.setData({
          importResult: result
        });
        
        wx.showToast({
          title: '导入成功',
        });
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      // 隐藏加载
      wx.hideLoading();
      
      console.error('导入Excel数据失败', error);
      wx.showToast({
        title: '导入Excel数据失败',
        icon: 'none'
      });
    }
  },

  /**
   * OCR拍照识别
   */
  takePhoto() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
      success: res => {
        const tempFilePath = res.tempFilePaths[0];
        
        this.setData({
          ocrImage: tempFilePath,
          ocrResult: null
        });
        
        // 识别图片
        this.recognizeImage(tempFilePath);
      }
    });
  },

  /**
   * 识别图片内容
   */
  async recognizeImage(imagePath) {
    try {
      // 设置加载状态
      this.setData({
        ocrLoading: true
      });
      
      // 调用服务识别试题
      const result = await questionService.recognizeQuestionByOCR(imagePath);
      
      // 结束加载状态
      this.setData({
        ocrLoading: false
      });
      
      if (result.success) {
        // 设置识别结果
        this.setData({
          ocrResult: result
        });
        
        // 如果识别成功，可以将结果填充到手动添加表单中
        if (result.question) {
          this.setData({
            'manualForm.stem': result.question.stem || '',
            'manualForm.options': result.question.options || ['', '', '', ''],
            'manualForm.answer': result.question.answer || '',
            'manualForm.type': result.question.type || 'single_choice'
          });
          
          // 切换到手动添加标签页
          this.setData({
            activeTab: 2
          });
        }
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      // 结束加载状态
      this.setData({
        ocrLoading: false
      });
      
      console.error('识别图片失败', error);
      wx.showToast({
        title: '识别图片失败',
        icon: 'none'
      });
    }
  },

  /**
   * 表单项输入事件
   */
  onInput(event) {
    const { field } = event.currentTarget.dataset;
    const { value } = event.detail;
    
    this.setData({
      [`manualForm.${field}`]: value
    });
  },

  /**
   * 选项输入事件
   */
  onOptionInput(event) {
    const { index } = event.currentTarget.dataset;
    const { value } = event.detail;
    
    // 更新选项数组
    const options = this.data.manualForm.options;
    options[index] = value;
    
    this.setData({
      'manualForm.options': options
    });
  },

  /**
   * 添加选项
   */
  addOption() {
    const options = this.data.manualForm.options;
    options.push('');
    
    this.setData({
      'manualForm.options': options
    });
  },

  /**
   * 删除选项
   */
  removeOption(event) {
    const { index } = event.currentTarget.dataset;
    const options = this.data.manualForm.options;
    
    // 至少保留2个选项
    if (options.length <= 2) {
      wx.showToast({
        title: '至少需要2个选项',
        icon: 'none'
      });
      return;
    }
    
    options.splice(index, 1);
    
    this.setData({
      'manualForm.options': options
    });
  },

  /**
   * 题型切换
   */
  onTypeChange(event) {
    const type = event.detail;
    
    this.setData({
      'manualForm.type': type
    });
    
    // 判断题直接设置选项
    if (type === 'true_false') {
      this.setData({
        'manualForm.options': ['正确', '错误']
      });
    } else if (type === 'fill_blank' || type === 'short_answer') {
      // 填空题和简答题不需要选项
      this.setData({
        'manualForm.options': []
      });
    } else if (this.data.manualForm.options.length === 0) {
      // 选择题至少需要4个选项
      this.setData({
        'manualForm.options': ['', '', '', '']
      });
    }
  },

  /**
   * 难度切换
   */
  onDifficultyChange(event) {
    const difficulty = parseInt(event.detail);
    
    this.setData({
      'manualForm.difficulty': difficulty
    });
  },

  /**
   * 显示知识点选择弹窗
   */
  showKnowledgePopup() {
    this.setData({
      showKnowledgePopup: true
    });
  },

  /**
   * 关闭知识点选择弹窗
   */
  closeKnowledgePopup() {
    this.setData({
      showKnowledgePopup: false
    });
  },

  /**
   * 选择知识点
   */
  onKnowledgeChange(event) {
    this.setData({
      'manualForm.knowledge': event.detail
    });
  },

  /**
   * 表单提交
   */
  async submitForm() {
    try {
      const { manualForm } = this.data;
      
      // 表单验证
      if (!manualForm.stem) {
        wx.showToast({
          title: '请输入题干',
          icon: 'none'
        });
        return;
      }
      
      if ((manualForm.type === 'single_choice' || manualForm.type === 'multiple_choice') && 
          (!manualForm.options || manualForm.options.length < 2)) {
        wx.showToast({
          title: '请至少输入2个选项',
          icon: 'none'
        });
        return;
      }
      
      if (!manualForm.answer) {
        wx.showToast({
          title: '请输入答案',
          icon: 'none'
        });
        return;
      }
      
      // 显示加载
      wx.showLoading({
        title: '保存中',
      });
      
      // 构建试题对象
      const question = {
        type: manualForm.type,
        subject: manualForm.subject,
        knowledge: manualForm.knowledge,
        difficulty: manualForm.difficulty,
        content: {
          stem: manualForm.stem,
          options: manualForm.options,
          answer: manualForm.answer,
          analysis: manualForm.analysis
        }
      };
      
      // 调用服务创建试题
      const result = await questionService.createQuestion(question);
      
      // 隐藏加载
      wx.hideLoading();
      
      if (result.success) {
        wx.showToast({
          title: '添加成功'
        });
        
        // 重置表单
        this.resetForm();
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      // 隐藏加载
      wx.hideLoading();
      
      console.error('提交表单失败', error);
      wx.showToast({
        title: '提交表单失败',
        icon: 'none'
      });
    }
  },

  /**
   * 重置表单
   */
  resetForm() {
    this.setData({
      manualForm: {
        type: 'single_choice',
        subject: this.data.subjects[this.data.subjectIndex],
        stem: '',
        options: ['', '', '', ''],
        answer: '',
        analysis: '',
        difficulty: 3,
        knowledge: []
      }
    });
  },

  /**
   * 返回试题管理页面
   */
  goBack() {
    wx.navigateBack();
  }
}) 